package cn.chengpengper.im.server.application.netty.runner;

import cn.chengpengper.im.server.application.netty.ImNettyServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;

/*@formatter:off*/

/**
 * ____________________
 * < 神兽护体，永无bug! >
 * --------------------
 *
 * @author huchengpeng
 * @version v1.0.0
 * @date 2024/11/17 01:29
 * @description 服务启动器
 */

/*@formatter:on*/

@Slf4j
@Component
public class ImServerRunner implements CommandLineRunner {

    @Autowired
    private List<ImNettyServer> imNettyServerList;

    public boolean isReady() {
        for (ImNettyServer imNettyServer : imNettyServerList) {
            if (!imNettyServer.isReady()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void run(String... args) throws Exception {
        // 启动每个服务
        if (CollectionUtils.isNotEmpty(imNettyServerList)) {
            imNettyServerList.forEach(ImNettyServer::start);
        }
    }

    @PreDestroy
    public void destory() {
        if (CollectionUtils.isNotEmpty(imNettyServerList)) {
            imNettyServerList.forEach(ImNettyServer::shutdown);
        }
    }
}
